<template>
  <div class="user-posts">
    <!-- 搜索区域 -->
    <el-card class="search-area">
      <el-form :inline="true" :model="queryParams" @submit.prevent="handleSearch">
        <el-form-item label="帖子标题">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入帖子标题"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="帖子分类">
          <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 帖子列表 -->
    <el-card v-loading="loading" class="post-list">
      <template v-if="postList.length">
        <div v-for="post in postList" :key="post.postId" class="post-item">
          <el-card shadow="hover">
            <div class="post-header">
              <div class="post-info">
                <el-tag size="small" type="success">{{ post.categoryName }}</el-tag>
                <span class="post-time">发布时间：{{ post.createTime }}</span>
              </div>
              <div class="post-stats">
                <span class="stat-item">
                  <el-icon><View /></el-icon>
                  {{ post.viewCount }}
                </span>
                <span class="stat-item">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ post.commentCount }}
                </span>
              </div>
            </div>
            <div class="post-content">
              <h3 class="post-title">{{ post.title }}</h3>
              <p class="post-summary">{{ post.content }}</p>
              <div v-if="post.images" class="post-images">
                <el-image
                  v-for="(image, index) in parseImages(post.images)"
                  :key="index"
                  :src="getImageUrl(image)"
                  :preview-src-list="parseImages(post.images).map(img => getImageUrl(img))"
                  fit="cover"
                  class="preview-image"
                />
              </div>
            </div>
            <div class="post-footer">
              <div class="actions">
                <el-button type="primary" @click="handleEdit(post)">编辑</el-button>
                <el-button type="danger" @click="handleDelete(post)">删除</el-button>
                <el-button @click="viewDetail(post)">查看详情</el-button>
              </div>
            </div>
          </el-card>
        </div>
      </template>
      <el-empty v-else description="暂无帖子" />
    </el-card>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      append-to-body
      @close="resetForm"
    >
      <el-form
        ref="postForm"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入帖子标题" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择帖子分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入帖子内容"
          />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            v-model:file-list="fileList"
            :action="uploadImgUrl"
            list-type="picture-card"
            :headers="headers"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, View, ChatDotRound } from '@element-plus/icons-vue'
import { listCategory } from '@/api/ich/category'
import { listUserPost, getPost, updatePost, deletePost } from '@/api/user/post'
import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'

const router = useRouter()
const loading = ref(false)
const total = ref(0)
const postList = ref([])
const categoryOptions = ref([])
const fileList = ref([])
const userStore = useUserStore()

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  categoryId: undefined,
  userId: userStore.id
})

// 表单参数
const form = ref({
  postId: undefined,
  title: undefined,
  categoryId: undefined,
  content: undefined,
  images: []
})

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度必须在2到50个字符之间', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '内容不能为空', trigger: 'blur' },
    { min: 10, max: 2000, message: '内容长度必须在10到2000个字符之间', trigger: 'blur' }
  ]
}

// 对话框
const dialog = ref({
  visible: false,
  title: ''
})

// 上传相关
const uploadImgUrl = import.meta.env.VITE_APP_BASE_API + '/system/forum/upload/image'
const headers = ref({ Authorization: 'Bearer ' + getToken() })

// 获取分类列表
const getCategories = async () => {
  try {
    const res = await listCategory()
    categoryOptions.value = res.rows
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('获取分类失败')
  }
}

// 获取帖子列表
const getList = async () => {
  loading.value = true
  try {
    const res = await listUserPost(queryParams.value)
    postList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    ElMessage.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleSearch = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    categoryId: undefined,
    userId: userStore.id
  }
  getList()
}

// 编辑按钮操作
const handleEdit = async (post) => {
  dialog.value = {
    visible: true,
    title: '编辑帖子'
  }
  try {
    const res = await getPost(post.postId)
    form.value = res.data
    fileList.value = form.value.images.map((url, index) => ({
      name: `图片${index + 1}`,
      url
    }))
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    ElMessage.error('获取帖子详情失败')
  }
}

// 删除按钮操作
const handleDelete = (post) => {
  ElMessageBox.confirm('确认要删除该帖子吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deletePost(post.postId)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      }
    } catch (error) {
      console.error('删除帖子失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 查看帖子详情
const viewDetail = (post) => {
  router.push(`/user/forum/post/${post.postId}`)
}

// 上传前处理
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response, file) => {
  if (response.code === 200) {
    form.value.images = form.value.images || []
    form.value.images.push(response.data)
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 移除图片
const handleUploadRemove = (file) => {
  const index = form.value.images.indexOf(file.response?.data || file.url)
  if (index > -1) {
    form.value.images.splice(index, 1)
  }
}

// 取消按钮
const cancel = () => {
  resetForm()
  dialog.value.visible = false
}

// 表单重置
const resetForm = () => {
  form.value = {
    postId: undefined,
    title: undefined,
    categoryId: undefined,
    content: undefined,
    images: []
  }
  fileList.value = []
}

// 提交表单
const submitForm = async () => {
  try {
    const res = await updatePost(form.value)
    if (res.code === 200) {
      ElMessage.success('更新成功')
      dialog.value.visible = false
      getList()
    } else {
      ElMessage.error(res.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新帖子失败:', error)
    ElMessage.error('更新失败')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 处理图片URL
const getImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) {
    return url
  }
  return import.meta.env.VITE_APP_BASE_API + (url.startsWith('/') ? url : '/' + url)
}

// 解析图片字符串为数组
const parseImages = (images) => {
  if (!images) return []
  try {
    return typeof images === 'string' ? JSON.parse(images) : images
  } catch (e) {
    return []
  }
}

onMounted(() => {
  getCategories()
  getList()
})
</script>

<style lang="scss" scoped>
.user-posts {
  padding: 20px;

  .search-area {
    margin-bottom: 20px;
  }

  .post-list {
    margin-bottom: 20px;

    .post-item {
      margin-bottom: 20px;

      .post-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .post-info {
          display: flex;
          align-items: center;
          gap: 15px;

          .post-time {
            color: #666;
            font-size: 14px;
          }
        }

        .post-stats {
          display: flex;
          align-items: center;
          gap: 15px;

          .stat-item {
            display: flex;
            align-items: center;
            gap: 5px;
            color: #666;
            font-size: 14px;
          }
        }
      }

      .post-content {
        .post-title {
          margin: 0 0 10px;
          font-size: 18px;
          font-weight: bold;
        }

        .post-summary {
          margin: 0 0 15px;
          color: #666;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }

        .post-images {
          display: flex;
          gap: 10px;

          .preview-image {
            width: 120px;
            height: 120px;
            border-radius: 4px;
          }
        }
      }

      .post-footer {
        display: flex;
        justify-content: flex-end;
        margin-top: 15px;
        padding-top: 15px;
        border-top: 1px solid #eee;

        .actions {
          .el-button {
            margin-left: 10px;
          }
        }
      }
    }
  }

  .pagination-container {
    text-align: center;
    margin-top: 20px;
  }

  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 100px;
    height: 100px;
  }
}
</style> 